import Row from "./Row.js"

/**
 * 块 多行组成一个块
 */
export default class Block{
    constructor(){
        this.list=[];
    }
    find(n){
        let res=this.list[n-1];
        if(res){
            return res;
        }
        return null;
    }
    save(n,data){
        this.list[n]=data;
    }
    addData(fileId,blockId,rowId,data){
        if(rowId!=null){
          return   this.list[rowId]=data;
        }else {
          let index=this.list.length;
             this.list.push(data)
            return index;
        }
    }
    saveData(fileId,blockId,rowId,data){
        if(rowId!=null){
            if(!this.list[blockId]){
                this.list[blockId]=new Row(0,0,0,0);
            }

            return  this.list[blockId].saveData(fileId,blockId,rowId,data);
        }else {
            this.list[blockId]=data;
        }
    }

    findData(fileId,blockId,rowId,func){
        let _this=this;
        if(rowId!=null){
            return this.list[blockId].findData(fileId,blockId,rowId,func);
        }
        if(func){
            return func(fileId,blockId,rowId,_this);
        }
        return this.list[blockId];
    }

    /**
      通过 固定位置的值 判断是否存在列表里面，并返回
     */
    isRows(a,b,c,d){
        let isMap=[,a,b,c,d];
        let isKey=[]
        let res=[];
        if(a){
            isKey.push(1)
        }
        if(b){
            isKey.push(2)
        }
        if(c){
            isKey.push(3)
        }
        if(d){
            isKey.push(4)
        }

        for(let i=0;i<this.list.length;i++){
            let row= this.list[i];
            let isNub=0;
            for(let n=0;n<isKey.length;n++){
                if( row.isValue(iskey[n],isMap[iskey[n]]) ){
                    isNub++;
                }
            }
            if(isNub == isKey.length){
                res.push(row)
            }
        }

        return res;

    }

    addRow(data){
      this.list.push(data);
    }
    //编码
    encoded(){
        let _this=this;
        if(  this.list.length==0){
            return "";
        }
        let res=""
        for(let i=0;i<_this.list.length;i++){
            let row =_this.list[i].encoded();
            res+=row+'b'
        }
        return res.substr(0,res.length-1)
    }
    //解码
    decode(words){
        let list =words.split("b")
        for(let l=0;l<list.length;l++){
          let row=new Row();

          row.decode(list[l])
            this.list.push(row);
        }

    }
}
